package com.hlj.ncp.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hlj.ncp.system.entity.SysUser;
import com.hlj.ncp.system.mapper.SysUserMapper;

/**
 * 用户认证服务
 */
@Service
public class UserAuthService implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    // 静态硬编码的管理员密码（已加密）用于演示
    private static final String ADMIN_PASSWORD = "$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2"; // admin123

    /**
     * 加载用户信息
     * 
     * @param username 用户名
     * @return 用户详情
     * @throws UsernameNotFoundException 用户不存在异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 尝试从数据库查询用户
        SysUser user = selectUserByUserName(username);
        
        // 如果找不到此用户，但用户名是admin（用于演示）
        if (user == null && "admin".equals(username)) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            
            // 使用预设的加密密码
            return new User(username, ADMIN_PASSWORD, authorities);
        }
        
        // 如果找到了用户，返回用户的信息
        if (user != null) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            
            if ("admin".equals(user.getUsername())) {
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }
            
            return new User(user.getUsername(), user.getPassword(), authorities);
        }
        
        throw new UsernameNotFoundException("用户名不存在");
    }
    
    /**
     * 根据用户名查询用户
     * 
     * @param username 用户名
     * @return 用户对象
     */
    private SysUser selectUserByUserName(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        return userMapper.selectOne(wrapper);
    }
} 